/**
 * Copyright &copy; 2014-2015 <a href="http://www.zhiqone.com">zhiqone</a> All rights reserved.
 */
package com.zcm.modules.center.service;

import java.security.MessageDigest;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import com.zcm.modules.center.dao.CenterUserDao;
import com.zcm.modules.center.entity.CenterUser;
import com.zcm.modules.center.utils.CenterLogUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zcm.common.persistence.Page;
import com.zcm.common.security.Digests;
import com.zcm.common.security.shiro.session.SessionDAO;
import com.zcm.common.service.BaseService;
import com.zcm.common.utils.CacheUtils;
import com.zcm.common.utils.Encodes;
import com.zcm.common.utils.IdGen;
import com.zcm.common.utils.StringUtils;

import com.zcm.modules.sys.dao.MenuDao;
import com.zcm.modules.sys.dao.RoleDao;
import com.zcm.modules.sys.entity.Menu;
import com.zcm.modules.sys.entity.Role;
import com.zcm.modules.center.dao.CenterUserRoleDao;
import com.zcm.modules.center.entity.CenterUserRole;
import com.zcm.modules.center.utils.CenterUserUtils;

/**
 * 系统管理，安全相关实体的管理类,包括用户、角色、菜单.
 * @author liangstc
 * @version 2013-12-05
 */
@Service
@Transactional(readOnly = true)
public class CenterService extends BaseService implements InitializingBean {
	
	
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	public static final int SALT_SIZE = 8;
	
	@Autowired
	private CenterUserDao userDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private MenuDao menuDao;
	@Autowired
	private SessionDAO sessionDao;

	
	public SessionDAO getSessionDao() {
		return sessionDao;
	}
 

	//-- User Service --//
	
	/**
	 * 获取用户
	 * @param id
	 * @return
	 */
	public CenterUser getUser(String id) {
		return CenterUserUtils.get(id);
	}

	/**
	 * 根据登录名获取用户
	 * @param loginName
	 * @return
	 */
	public CenterUser getUserByLoginName(String loginName) {
		return CenterUserUtils.getByLoginName(loginName);
	}
	/**
	 * 根据手机号获取用户数量
	 * @param mobile
	 * @return
	 */
	public CenterUser getUserByMobile(String mobile) {
		return CenterUserUtils.getByMobile(mobile);
	}
	public CenterUser getuserByUnionID(String unionid) {
		return CenterUserUtils.getByUnionID(unionid);
	}
	public Page<CenterUser> findUser(Page<CenterUser> page, CenterUser user) {
		// 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
		user.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "a"));
		// 设置分页参数
		user.setPage(page);
		// 执行分页查询
		page.setList(userDao.findList(user));
		return page;
	}
	
	/**
	 * 无分页查询人员列表
	 * @param user
	 * @return
	 */
	public List<CenterUser> findUser(CenterUser user){
		// 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
		user.getSqlMap().put("dsf", dataScopeFilter(user.getCurrentUser(), "o", "a"));
		List<CenterUser> list = userDao.findList(user);
		return list;
	}

//
//
//	@Transactional(readOnly = false)
//	public int saveUser(CenterUser user) {
//		//user.setId(IdGen.uuid());
//		user.preInsert();
//		int i = userDao.insert(user);
//		if (StringUtils.isNotBlank(user.getId())){
//			CenterUserRole centerUserRole = new CenterUserRole();
//			centerUserRole.setUser(user);
//			centerUserRole.setRoleId("7e4c39cdfacb4f2cb8766cd43a076390");
//			centerUserRoleDao.insert(centerUserRole);
//		}
//		return i ;
//	}
	
//	@Transactional(readOnly = false)
//	public int saveCenterUser(CenterUser user) {
//		user.setId(IdGen.uuid());
//		CenterUserRole centerUserRole = new CenterUserRole();
//		centerUserRole.setUser(user);
//		SysParam sysParam = new SysParam();
//		String rolename = "center_"+user.getUserType()+"_"+user.getCompanyType();
//		sysParam = sysParamDao.getByName(rolename);
//		centerUserRole.setUser(user);
//		centerUserRole.setRoleId(sysParam.getParamvalue());
//		centerUserRoleDao.insert(centerUserRole);
//		return userDao.insert(user);
//	}
	
	@Transactional(readOnly = false)
	public void updateUserInfo(CenterUser user) {
		user.preUpdate();
		//userDao.updateUserInfo(user);
		// 清除用户缓存
		CenterUserUtils.clearCache(user);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}
	
	@Transactional(readOnly = false)
	public void deleteUser(CenterUser user) {
		userDao.delete(user);
		 
		// 清除用户缓存
		CenterUserUtils.clearCache(user);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}
	
//	/**
//	 * 修改密码
//	 * @param centerUser
//	 */
//	@Transactional(readOnly = false)
//	public int updatePasswordById(CenterUser centerUser) {
//		int i = userDao.updatePasswordById(centerUser);
//		return i;
//	}
//	@Transactional(readOnly = false)
//	public int updateUnionidById(CenterUser centeruser) {
//		int i = userDao.updateUnionidById(centeruser);
//		return i;
//
//	}
//	/**
//	 * 修改密码
//	 * @param centerUser
//	 */
//	@Transactional(readOnly = false)
//	public int updatePasswordByLoginName(CenterUser centerUser) {
//		int i = userDao.updatePasswordByLoginName(centerUser);
//		return i;
//	}
//
//	@Transactional(readOnly = false)
//	public void updateUserLoginInfo(CenterUser user) {
//
//		// 更新本次登录信息
//		user.setLoginIp(CenterUserUtils.getSession().getHost());
//		user.setLoginDate(new Date());
//		userDao.updateLoginInfo(user);
//	}
//
	/**
	 * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
	 */
	public static String entryptPassword(String plainPassword) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
		return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword);
	}
	
	/**
	 * MD5密码加密
	 * @param password
	 * @return
	 */
	public static String getMD5(String password) {
		String md5 = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(password.getBytes("utf-8"));
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; i++) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
						.toUpperCase().substring(1, 3));
			}
			md5 = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return md5;

	}

	
	/**
	 * 验证密码
	 * @param plainPassword 明文密码
	 * @param password 密文密码
	 * @return 验证成功返回true
	 */
	public static boolean validatePassword(String plainPassword, String password) {
		byte[] salt = Encodes.decodeHex(password.substring(0,16));
		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
		return password.equals(Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword));
	}
	
	/**
	 * 获得活动会话
	 * @return
	 */
	public Collection<Session> getActiveSessions(){
		return sessionDao.getActiveSessions(false);
	}
	
	//-- Role Service --//
	
	public Role getRole(String id) {
		return roleDao.get(id);
	}

	public Role getRoleByName(String name) {
		Role r = new Role();
		r.setName(name);
		return roleDao.getByName(r);
	}
	
	public Role getRoleByEnname(String enname) {
		Role r = new Role();
		r.setEnname(enname);
		return roleDao.getByEnname(r);
	}
	
	public List<Role> findRole(Role role){
		return roleDao.findList(role);
	}
	
	public List<Role> findAllRole(){
		return CenterUserUtils.getRoleList();
	}
	
	@Transactional(readOnly = false)
	public void saveRole(Role role) {
		if (StringUtils.isBlank(role.getId())){
			role.preInsert();
			roleDao.insert(role); 
		}else{
			role.preUpdate();
			roleDao.update(role);
		}
		// 更新角色与菜单关联
		roleDao.deleteRoleMenu(role);
		if (role.getMenuList().size() > 0){
			roleDao.insertRoleMenu(role);
		}
		// 更新角色与部门关联
		roleDao.deleteRoleOffice(role);
		if (role.getOfficeList().size() > 0){
			roleDao.insertRoleOffice(role);
		} 
		// 清除用户角色缓存
		CenterUserUtils.removeCache(CenterUserUtils.CACHE_ROLE_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}

	@Transactional(readOnly = false)
	public void deleteRole(Role role) {
		roleDao.delete(role);
		 
		// 清除用户角色缓存
		CenterUserUtils.removeCache(CenterUserUtils.CACHE_ROLE_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}
//
//	@Transactional(readOnly = false)
//	public Boolean outUserInRole(Role role, CenterUser user) {
//		List<Role> roles = user.getRoleList();
//		for (Role e : roles){
//			if (e.getId().equals(role.getId())){
//				roles.remove(e);
//				saveUser(user);
//				return true;
//			}
//		}
//		return false;
//	}
////
////	@Transactional(readOnly = false)
////	public CenterUser assignUserToRole(Role role, CenterUser user) {
////		if (user == null){
////			return null;
////		}
////		List<String> roleIds = user.getRoleIdList();
////		if (roleIds.contains(role.getId())) {
////			return null;
////		}
////		user.getRoleList().add(role);
////		saveUser(user);
////		return user;
////	}

	//-- Menu Service --//
	
	public Menu getMenu(String id) {
		return menuDao.get(id);
	}

	public List<Menu> findAllMenu(){
		return CenterUserUtils.getMenuList();
	}
	
	@Transactional(readOnly = false)
	public void saveMenu(Menu menu) {
		
		// 获取父节点实体
		menu.setParent(this.getMenu(menu.getParent().getId()));
		
		// 获取修改前的parentIds，用于更新子节点的parentIds
		String oldParentIds = menu.getParentIds(); 
		
		// 设置新的父节点串
		menu.setParentIds(menu.getParent().getParentIds()+menu.getParent().getId()+",");

		// 保存或更新实体
		if (StringUtils.isBlank(menu.getId())){
			menu.preInsert();
			menuDao.insert(menu);
		}else{
			menu.preUpdate();
			menuDao.update(menu);
		}
		
		// 更新子节点 parentIds
		Menu m = new Menu();
		m.setParentIds("%,"+menu.getId()+",%");
		List<Menu> list = menuDao.findByParentIdsLike(m);
		for (Menu e : list){
			e.setParentIds(e.getParentIds().replace(oldParentIds, menu.getParentIds()));
			menuDao.updateParentIds(e);
		}
		// 清除用户菜单缓存
		CenterUserUtils.removeCache(CenterUserUtils.CACHE_MENU_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
		// 清除日志相关缓存
		CacheUtils.remove(CenterLogUtils.CACHE_MENU_NAME_PATH_MAP);
	}

	@Transactional(readOnly = false)
	public void updateMenuSort(Menu menu) {
		menuDao.updateSort(menu);
		// 清除用户菜单缓存
		CenterUserUtils.removeCache(CenterUserUtils.CACHE_MENU_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
		// 清除日志相关缓存
		CacheUtils.remove(CenterLogUtils.CACHE_MENU_NAME_PATH_MAP);
	}

	@Transactional(readOnly = false)
	public void deleteMenu(Menu menu) {
		menuDao.delete(menu);
		// 清除用户菜单缓存
		CenterUserUtils.removeCache(CenterUserUtils.CACHE_MENU_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
		// 清除日志相关缓存
		CacheUtils.remove(CenterLogUtils.CACHE_MENU_NAME_PATH_MAP);
	}
	
	 
	public static boolean printKeyLoadMessage(){
	 
		return true;
	}


	@Override
	public void afterPropertiesSet() throws Exception {
		
	}

	static public void main(String [] args){
		System.out.println(getMD5("Shanghai"));
	}
//	/**
//	 * 修改头像
//	 * @param centerUser
//	 * @return
//	 */
//	@Transactional(readOnly = false)
//	public int updatephotoById(CenterUser centerUser) {
//		int i = userDao.updatePhotoById(centerUser);
//		return i;
//	}
//
//	@Transactional(readOnly = false)
//	public void insertRole(CenterUserRole centerUserRole) {
//
//		centerUserRoleDao.insert(centerUserRole);
//	}
//
//	@Transactional(readOnly = false)
//	public void removeUserRole(CenterUserRole centerUserRole) {
//
//		centerUserRoleDao.deleteCenterUserRole(centerUserRole);
//	}
//
//
//	public CenterUserRole findRoleByUser(CenterUserRole centerUserRole) {
//		return centerUserRoleDao.findRoleByUser(centerUserRole);
//	}

//
//	public CenterUser getUserByPhoneNum(String phoneNum) {
//		return CenterUserUtils.getUserByPhoneNum(phoneNum);
//	}

	
	///////////////// Synchronized to the Activiti //////////////////
	
	// 已废弃，同步见：ActGroupEntityServiceFactory.java、ActUserEntityServiceFactory.java

 
	
 
	
	///////////////// Synchronized to the Activiti end //////////////////
	
}
